package com.simblog.oaknt.service.impl;


import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.sql.dialect.odps.visitor.OdpsASTVisitor;
import com.alibaba.dubbo.config.annotation.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.simblog.common.constans.ActionCodeConstants;
import com.simblog.oaknt.domain.User;
import com.simblog.oaknt.domain.VerificationRecord;
import com.simblog.oaknt.mapper.UserMapper;
import com.simblog.oaknt.mapper.VerificationRecordMapper;
import com.simblog.oaknt.service.IVerificationRecordService;
import com.sun.org.apache.regexp.internal.recompile;

/**
 * 
 * <br>
 * <b>功能：</b>VerificationRecordServiceImpl<br>
 * <b>作者：</b>yc<br>
 * <b>日期：</b> Thu Oct 13 22:46:18 CST 2016 <br>
 * <b>版权所有： 2015,dd5s.com<br>
 */ 
@Service(interfaceClass=IVerificationRecordService.class, timeout=30000)
public class VerificationRecordServiceImpl extends BaseServiceImpl<VerificationRecord> implements IVerificationRecordService{
	
	private final static Logger log= LoggerFactory.getLogger(VerificationRecordServiceImpl.class);
	
	@Autowired
    private VerificationRecordMapper mapper;
	@Autowired
	private UserMapper userMapper;
		
	public VerificationRecordMapper getMapper() {
		return mapper;
	}
	
	@Override
	public String addRegisterRecord(User user) {
		
		invalidRecords(user.getId(), ActionCodeConstants.VERIFICATION_REGISTER);
		
		UUID uuid = UUID.randomUUID();
		
		VerificationRecord record = new VerificationRecord();
		record.setUuid(uuid.toString());
		Date now = new Date();
		record.setCreateTime(now);

		//把验证截止时间往后推
		record.setLastValidTime(DateUtils.addMinutes(now, ActionCodeConstants.VERIFICATION_REGISTER_LONG));
		
		//设为未验证
		record.setIsVerificate("0");
		//设为有效
		record.setIsInvalid("0");
		//设置类型
		record.setType(ActionCodeConstants.VERIFICATION_REGISTER);
				
		record.setUserId(user.getId());
		record.setEmail(user.getEmail());

		record.setIsDelete("0");
		
		if(mapper.insert(record) > 0)
			return uuid.toString();
		else
			return null;
	}
	
	@Override
	public String addPasswordRecord(User user) {
		
		invalidRecords(user.getId(), ActionCodeConstants.VERIFICATION_PASSWORD);
		
		UUID uuid = UUID.randomUUID();
		
		VerificationRecord record = new VerificationRecord();
		record.setUuid(uuid.toString());
		Date now = new Date();
		record.setCreateTime(now);

		//把验证截止时间往后推
		record.setLastValidTime(DateUtils.addMinutes(now, ActionCodeConstants.VERIFICATION_PASSWORD_LONG));
		
		//设为未验证
		record.setIsVerificate("0");
		//设为有效
		record.setIsInvalid("0");
		//设置类型
		record.setType(ActionCodeConstants.VERIFICATION_PASSWORD);
		
		record.setUserId(user.getId());
		record.setEmail(user.getEmail());
		
		record.setIsDelete("0");
		
		if(mapper.insert(record) > 0)
			return uuid.toString();
		else
			return null;
	}
	
	public void invalidRecords(Long userId, String type){
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("type", type);
		params.put("isVerificate", "0");
		params.put("IsInvalid", "0");
		
		List<VerificationRecord> list = mapper.query(params);
		
		if(list == null)
			return ;
		else{
			for(VerificationRecord record : list){
				record.setIsInvalid("1");
				mapper.updateByPrimaryKey(record);
			}
		}
	}

	@Override
	public VerificationRecord findRecordByUuid(String uuid) {
		return mapper.selectByUUID(uuid);
	}

	@Override
	public boolean verificateRegister(VerificationRecord record) {
		if(!record.getType().equals(ActionCodeConstants.VERIFICATION_REGISTER)){
			log.error("{}的验证请求失败：{}",record.getUuid(),"不是注册验证.");
			return false;
		}
		if("1".equals(record.getIsVerificate())){
			log.error("{}的验证请求失败：{}",record.getUuid(),"已经验证过.");
			return false;
		}
		if("1".equals(record.getIsInvalid())){
			log.error("{}的验证请求失败：{}",record.getUuid(),"已经失效.");
			return false;
		}
		
		Date startDate = record.getCreateTime();
		Date endDate = record.getLastValidTime();
		Date now = new Date();
		if(now.before(startDate) || now.after(endDate)){
			log.error("{}的验证请求失败：{}",record.getUuid(),"不在有效验证时间内.");
			return false;
		}
		
		record.setIsVerificate("1");
		record.setVerificateTime(now);
		record.setIsInvalid("1");
		mapper.updateByPrimaryKey(record);
		
		User user = userMapper.selectByPrimaryKey(record.getUserId());
		user.setIsVerify("1");
		userMapper.updateByPrimaryKey(user);
		
		return true;
	}

	@Override
	public boolean verificatePassword(VerificationRecord record) {
		
		if(!record.getType().equals(ActionCodeConstants.VERIFICATION_PASSWORD)){
			log.error("{}的验证请求失败：{}",record.getUuid(),"不是重置密码验证.");
			return false;
		}
		if("1".equals(record.getIsVerificate())){
			log.error("{}的验证请求失败：{}",record.getUuid(),"已经验证过.");
			return false;
		}
		if("1".equals(record.getIsInvalid())){
			log.error("{}的验证请求失败：{}",record.getUuid(),"已经失效.");
			return false;
		}
		
		Date startDate = record.getCreateTime();
		Date endDate = record.getLastValidTime();
		Date now = new Date();
		if(now.before(startDate) || now.after(endDate)){
			log.error("{}的验证请求失败：{}",record.getUuid(),"不在有效验证时间内.");
			return false;
		}
		
		record.setIsVerificate("1");
		record.setVerificateTime(now);
		record.setIsInvalid("1");
		mapper.updateByPrimaryKey(record);
		
		return true;
	}

	@Override
	public boolean isAllowVerOfRegist(String email) {
		
		if(!checktimes(email, "1"))
			return false;
		
		Map<String, Object> params = new HashMap<>();
		params.put("email", email);
		params.put("type", "1");
		params.put("isVerificate", "0");
		
		List<VerificationRecord> list = mapper.query(params);
		
		if(list == null || list.size() == 0)
			return true;
		else{
			Date old = list.get(0).getCreateTime();
			Date now = new Date();
			long between = now.getTime() - old.getTime();
			if(between > ActionCodeConstants.VERIFICATION_INTERVAL * 1000)
				return true;
			else
				return false;
		}
	}

	@Override
	public boolean isAllowVerOfPasswd(String email) {
		
		if(!checktimes(email, "2"))
			return false;
		
		Map<String, Object> params = new HashMap<>();
		params.put("email", email);
		params.put("type", "2");
		params.put("isVerificate", "0");
		
		List<VerificationRecord> list = mapper.query(params);
		
		if(list == null || list.size() == 0)
			return true;
		else{
			Date old = list.get(0).getCreateTime();
			Date now = new Date();
			long between = now.getTime() - old.getTime();
			if(between > ActionCodeConstants.VERIFICATION_INTERVAL * 1000)
				return true;
			else
				return false;
		}
	}
	
	/**
	 * 验证当日邮件次数
	 * @return
	 */
	private boolean checktimes(String email, String type){
		Map<String, Object> params = new HashMap<>();
		params.put("email", email);
		params.put("type", type);
		params.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		
		List<VerificationRecord> list = mapper.query(params);
		
		if(list != null && list.size() >= ActionCodeConstants.VERIFICATION_TIME)
			return false;
		else
			return true;
	}

}
